package com.liusy.serachengine;



import java.io.File;
import java.util.List;
import java.util.Map;


import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.Term;

import com.liusy.taskengine.executemodel.AbstractExecuteModel;


/**
 * 
 * 文件目录索引创建者
 * 
 * @author liusy 2013-02-19
 *
 */
public class IndexModel extends AbstractIndexModel{
  

	private static Logger log = Logger.getLogger(AbstractExecuteModel.class);


	public IndexModel(String indexPath) {
		
		super("file\\"+indexPath);
	}
	
	
	/**
	 * 多例 
	 * 
	 * @param indexPath
	 * @return IndexModel
	 */
	public static IndexModel getIndexModel(String indexPath)
	{
		SerachIndex serachIndex = SerachIndex.getSerachIndex();
		IIndexModel indexModel = serachIndex.getIndexModel(indexPath);
		if(null==indexModel)
		{
			indexModel = new IndexModel(indexPath);
			serachIndex.putIndexModel(indexModel);
		}
		return  (IndexModel) indexModel;
	}
	 

	/**
	 * 创建建索引
	 * 
	 * @param writer
	 * @param Object
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public void WriterDoc(IndexWriter writer, Object obj) {
		try {
			Document doc = null;
			String id = "";
			if(obj instanceof File)
			{
				File file = (File) obj; 
				if (file.canRead()) {
					if (file.isDirectory()) {
						String[] files = file.list();
						if (files != null) {
							for (int i = 0; i < files.length; i++) {
								WriterDoc(writer, new File(file, files[i]));
							}
						}
					} else {
							doc = this.getConvertModel().ObjectConvertDoc(file);
							id = file.getPath();
					}
				}
			}else if(obj instanceof List){
				List list = (List) obj; 
				for (int i = 0; i < list.size(); i++) {
					WriterDoc(writer, list.get(i));
				}
			}else
			{
				doc = this.getConvertModel().ObjectConvertDoc(obj);
				if(obj instanceof Map)
				{
					try {
						id =String.valueOf(((Map)obj).get("id"));
					} catch (Exception e) {
						log.info("Map 缺少主键id......!将无法更新该文档！");
					}
				}
			}
			if(null==doc)
				return;
			if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
				log.info("正在路径为：“"+super.indexPath+"” 下[创建]索引!");
				writer.addDocument(doc);
			} else {
				if(id.equals(""))
					return;
				log.info("正在路径为：“"+super.indexPath+"” 下[更新]索引!");
				writer.updateDocument(new Term("id", id),doc);
			}
		} catch (Exception e) {
			log.info(e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	


}
